﻿using Common.Infrastructure.Structs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace Common.Infrastructure.Utils
{
    public static class MessageStorageUtils
    {
        private static List<LibMessageFormat> formats = new List<LibMessageFormat>();

        public static string GetMessageFormat(string code, string lang)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new CommonException(" message code is null");
            }

            var f = formats.FirstOrDefault(t => string.Compare(t.Code, code, true) == 0);
            if (f == null)
            {
                throw new CommonException(" message code[" + code + "] is not exist");
            }

            var ret = f.GetFormat(lang);
            return string.IsNullOrEmpty(ret) ? throw new CommonException("error message lang " + lang) : ret;
        }

        public static void AddMessageFormat(LibMessageFormat format)
        {
            if (string.IsNullOrEmpty(format.Code))
            {
                return;
            }

            var old = formats.FirstOrDefault(t => string.Compare(t.Code, format.Code, true) == 0);
            if (old != null)
            {
                formats.Remove(old);
            }

            formats.Add(format);
        }

        public static void InitMessage()
        {
            DoInitMessageFormat();
        }

        private static void DoInitMessageFormat()
        {
            var files = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, "Message*.xml");
            foreach (var file in files)
            {
                XmlDocument xx = new XmlDocument();
                xx.Load(file);
                var x1 = xx.DocumentElement;
                var xs = x1.GetElementsByTagName("message");
                foreach (var x in xs)
                {
                    var node = (XmlElement)x;
                    var name = node.GetAttribute("name");
                    if (string.IsNullOrEmpty(name))
                    {
                        continue;
                    }

                    LibMessageFormat access = new LibMessageFormat
                    {
                        Code = name
                    };

                    var fields = node.GetElementsByTagName("item");
                    foreach (var f in fields)
                    {
                        var fieldNode = (XmlElement)f;
                        var lang = fieldNode.GetAttribute("lang");
                        access.AddFormat(lang, fieldNode.InnerText);
                    }

                    AddMessageFormat(access);
                }
            }
        }
    }
}
